// couponPack/pages/couponReceive/couponReceive.js
import { numberTransform } from "../../../utils/util";
import { mallApi } from "../../../api/index";
import { _requestSubscribeMessage } from '../../../utils/_requestSubscribeMessage';
import { toast } from '../../../utils/modal';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponReceiveShow: false,
    userInfo: {},
    shareInfo: {},
    coupon_type: '',
    coupon_id: 0,
    received_id: 0,
    conponList: [],
    goods: [],
    paginate: {
      currentPage: 0,
      hasMorePages: 1
    },
    canShare: false,
    // isSubscribeCoupon: false,
    status: 0,
    timer: null,
    showGuide: false,
  },
  // 获取优惠券信息
  getData() {
    mallApi.couponShareInfo({
      type: this.data.coupon_type, //coupon:优惠券  coupon_group:优惠券礼包
      resource_id: this.data.coupon_id
    }, {}, { showLoading: false })
      .then((res) => {
        this.setData({
          conponList: res.list,
          canShare: res.can_share,
          status: res.status // 10-可领取 20-已领取 30-已过期
        })
        // if (res.status === 30) {
        //   this.getIndexFeed();
        // }
      })
  },

  //点击领取优惠券
  async recriveClick() {
    let self = this
    let { conponList } = self.data
    // let len = conponList.length
    let id = conponList[0].id
    // let url = URL_COUPON_RECEIVE, param = { coupon_id: id }
    // if (len > 1) {
    //   url = URL_COUPON_DELIVER
    //   param = {
    //     coupon_group_id: this.data.coupon_id
    //   }
    // }
    let res = await mallApi.couponDeliver({
      coupon_id: id,
    })
    this.setData({
      received_id: res.received_id
    })
    this.checkSubscribe()
    // self.setData({
    //   couponReceiveShow: true
    // })
    // self.data.timer = setTimeout(function () {
    // self.setData({
    //   couponReceiveShow: true
    // })
    // self.goUse()
    // }, 2000)
  },
  onClosePopup() {
    wx.setStorageSync('couponSubscribeGuide', true)
    this.setData({
      showGuide: false
    })
  },
  async checkSubscribe() {
    const received_id = this.data.received_id
    let res = await mallApi.getSubscribeStatus({
      resource_type: 'coupon_expired',
      resource_id: received_id
    })
    if (res.subscribed) {
      // toast("已设置过期提醒啦");
      self.goUseTimer()
      return
    } else {
      let couponSubscribeGuide = wx.getStorageSync('couponSubscribeGuide') || false
      if (!couponSubscribeGuide) {
        this.setData({
          showGuide: true
        })
      }
      this.onSubscribe()
    }
  },
  async onSubscribe() {
    let self = this
    const received_id = this.data.received_id
    // let tmplIds = ['1dN12xV_1KrzsH0JA1lraqyrwGWcNMBphf_j1DO18q4'] //优惠券领取
    let tmplIds = ['L_3UJCQTPjZNuATuofu_Tv3-8bW5a9wBgE3Z84Skx-g'] //优惠券过期
    _requestSubscribeMessage(tmplIds,
      (res, isAllow) => {
        console.log('res', res);
        if (isAllow) {
          mallApi.postSubscribe({
            resource_type: 'coupon_expired',
            resource_id: received_id
          })
        }
        // 关闭订阅引导
        if (self.data.showGuide) {
          self.onClosePopup()
        }
        self.goUseTimer()
      }, (err) => {
        console.log('err', err)
      })
  },
  goUseTimer() {
    let self = this
    // wx.showToast({
    //   title: '领取成功',
    //   icon: 'success',
    //   duration: 2000,
    // })
    self.setData({
      couponReceiveShow: true
    })
    self.data.timer = setTimeout(function () {
      self.setData({
        couponReceiveShow: false
      })
      self.goUse()
    }, 2000)
  },
  //点击去使用优惠券
  goUse() {
    let { conponList } = this.data
    let len = conponList.length
    if (len > 1) {
      wx.reLaunch({
        url: '/pages/home/home',
      })
    } else {
      //单个优惠券
      let show_undertake = conponList[0].show_undertake;  //是否展示承接商品
      let type = conponList[0].use_limit_type;  //优惠券类型
      if (show_undertake) {
        let id = conponList[0].id
        wx.navigateTo({
          url: `../couponCanuse/couponCanuse?coupon_id=${id}&show_undertake=undertake`
        });
        return;
      }

      if (type === 10) {
        // 10 全部商品可用
        wx.reLaunch({
          url: '/pages/home/home',
        })
      } else if (type === 20) {
        // 20 部分商品可用
        let id = conponList[0].id
        wx.navigateTo({
          url: `../couponCanuse/couponCanuse?coupon_id=${id}`
        });
      } else if (type === 30) {
        // 30 单个商品可用
        let product_id = conponList[0].limit_product_id
        wx.navigateTo({
          url: `/pages/goodsDetail/goodsDetail?product_id=${product_id}`
        })
      }
    }
  },
  async getUserInfo() {
    try {
      let res = wx.getStorageSync('userInfo');
      if (!res) {
        res = await request.httpGet(URL_USER_INFO);
      }
      wx.setStorageSync('userInfo', res);
      this.setData({
        userInfo: res,
      });
    } catch (e) { }
  },
  showInfoBtn(e) {
    if (e.detail.errMsg == 'getUserInfo:ok') {
      let userInfo = {
        "avatar": e.detail.userInfo.avatarUrl,
        "nickname": e.detail.userInfo.nickName,
        "font_size": wx.getSystemInfoSync().fontSizeSetting,
        "gender": e.detail.userInfo.gender,
        "province": e.detail.userInfo.province,
        "city": e.detail.userInfo.city,
        "encryptedData": e.detail.encryptedData,
        "iv": e.detail.iv,
      }
      request.httpPost(URL_USER_INFO, userInfo, {}, {
        showLoading: false
      }).then(res => {
        this.data.userInfo.has_unionid = 1
        this.setData({
          userInfo: this.data.userInfo,
        });
        this.recriveClick();
      })
    }
  },
  // 获取首页推荐数据
  getIndexFeed() {
    const self = this;
    request.httpGet(URL_INDEX_FEEDS, {
      page: +this.data.paginate.currentPage + 1,
      page_size: 10,
      cate_id: 1
    }, {}, { showLoading: false })
      .then((res) => {
        // 本页商品去重 start
        let currentPageList = [],
          currentPageListIds = [];
        res.list.forEach(item => {
          if (currentPageListIds.indexOf(item.id) < 0 && !item.type && !item.is_reductions) {
            item.show = false;
            currentPageListIds.push(item.id);
            currentPageList.push(item);
          }
        });
        // 本页商品去重 end

        let list = this.data.goods;
        if (parseInt(res.paginate.currentPage) !== 1) {
          // 如果是下拉刷新 拼在后
          let listIds = list.map(item => {
            return item.id;
          });
          currentPageList.forEach(item => {
            if (listIds.indexOf(item.id) < 0) {
              item.show = false;
              (item.sold_count = numberTransform(item.sold_count)),
                list.push(item);
            }
          });
        } else {
          // 如果是第一页 清空之前的数据
          list = currentPageList.map(el => ({
            ...el,
            sold_count: numberTransform(el.sold_count),
          }));
        }

        self.setData({
          goods: list,
          paginate: res.paginate
        });
      }).catch((err) => {
      });
  },
  goGoodsDetail(e) {
    let id = e.currentTarget.dataset.id
    let show_source = e.currentTarget.dataset.trace_id ? 1 : 0;
    let trace_info = e.currentTarget.dataset.trace_info || '';
    // sendEvent(activityPack.recommendGoodsClick({
    //   product_id: id,
    //   show_source: show_source,
    // }))
    wx.navigateTo({
      url: `/pages/goodsDetail/goodsDetail?product_id=${id}&show_source=${show_source}&trace_info=${trace_info}`
    })
  },
  // 获取分享的信息
  getShareInfo() {
    request.httpGet(URL_SHARE_INFO, {
      type: 'path_couponReceive',
      resource_id: this.data.coupon_id,
      coupon_type: this.data.coupon_type
    }, {}, {
      showLoading: false
    }).then(resp => {
      this.data.shareInfo = resp
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      coupon_type: options.coupon_type,
      coupon_id: options.coupon_id
    }, () => {
      // this.getUserInfo();
      // this.getShareInfo();
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      couponReceiveShow: false
    })
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

    if (this.data.timer) {
      clearTimeout(this.data.timer)
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // let { paginate, status, goods } = this.data
    // if (+paginate.hasMorePages === 1 && status === 30 && goods.length > 0) {
    //   //加载更多
    //   this.getIndexFeed();
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { coupon_type, coupon_id, shareInfo, canShare } = this.data
    let path = `/couponPack/pages/couponReceive/couponReceive?coupon_type=${coupon_type}&coupon_id=${coupon_id}`
    console.log(canShare, path)
    return {
      title: "在家染发，安全染发" || "",
      path: canShare ? path : "/pages/home/home" || "",
      imageUrl: "https://ranboss.oss-cn-beijing.aliyuncs.com/image/quan.png",
    }
  }
})
